package org.enhance.web.util;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.enhance.common.exception.AssertionException;
import org.enhance.web.common.WebCommonConst;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestUtil {

	private RequestUtil() {
		throw new IllegalStateException("Utility class");
	}

	public static String getSlbId(HttpServletRequest request) {
		String slbId = request.getHeader("SLB-ID");
		return StringUtils.isNotBlank(slbId) ? slbId : StringUtils.EMPTY;
	}

	public static String getToken(HttpServletRequest request) {

		String token = request.getParameter(WebCommonConst.KEY_TOKEN_HEADER);
		if (StringUtils.isEmpty(token)) {
			token = request.getHeader(WebCommonConst.KEY_TOKEN_HEADER);
		}
		if (StringUtils.isEmpty(token)) {
			token = getCookieValue(WebCommonConst.KEY_TOKEN_HEADER);
		}
		return token;
	}

//    public static void addCookie(String key, String value) {
//        Integer expire = -1;
//		String expireStr = SpringUtil.getProperty("token.expire");
//        if (StringUtils.isNotEmpty(expireStr)) {
//            expire = Integer.valueOf(expireStr);
//        }
//        Cookie cookie = new Cookie(key, value);
//        cookie.setMaxAge(expire);
//        cookie.setPath("/");
//        getResponse().addCookie(cookie);
//    }

	public static boolean isAjax(HttpServletRequest request) {
		return StringUtils.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest");
	}

	public static void sendRedirect(HttpServletResponse response, String redirectUrl) {
		try {
			// 设置跳转地址
			response.setHeader("redirectUrl", redirectUrl);
			response.flushBuffer();
		} catch (IOException ex) {
			throw new AssertionException(ex);
		}
	}

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	private static String getCookieValue(String key) {
		Cookie[] cookies = getRequest().getCookies();
		String value = null;
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (key.equals(cookie.getName())) {
					value = cookie.getValue();
				}
			}
		}
		return value;
	}

}